package com.hzy.es.service;

import com.hzy.es.entity.Person;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class Template {
    /**
     * ElasticsearchTemplate和ElasticsearchRestTemplate实现ElasticsearchOperations接口
     */
    @Resource
    private ElasticsearchOperations elasticsearchOperations;

    public String save(Person person) {
        IndexQuery indexQuery = new IndexQueryBuilder()
                .withId(person.getId())
                .withObject(person)
                .build();
        String documentId = elasticsearchOperations.index(indexQuery, IndexCoordinates.of("indexName"));
        return documentId;
    }

    public Person findById(String id) {
        Person person = elasticsearchOperations.get(id, Person.class, IndexCoordinates.of("indexName"));
        return person;
    }

    /**
     * 自己看对象就可以了，有很多方法
     */
    public void method(){

        List<String> documentIds = elasticsearchOperations.bulkIndex(new ArrayList<IndexQuery>(), IndexCoordinates.of("indexName"));

        UpdateQuery updateQuery = UpdateQuery.builder("id")
                .withDocument(Document.from(new HashMap<>()))
                .build();
        elasticsearchOperations.bulkUpdate(new ArrayList<UpdateQuery>(), IndexCoordinates.of("indexName"));
    }
}
